$(document).ready(function() {
    $('#project-name').val('');
    loadSiteTable();
    reloadTree();
    $('#reset').click();
    /*日历插件*/
    layui.use('laydate', function() {
        var laydate = layui.laydate;
        //执行一个laydate实例
        laydate.render({
            elem: '#start-date-input',
        });
        laydate.render({
            elem: '#finish-date-input',
        });
		laydate.render({
		    elem: '#safetySupervisionDate-date-input',
		});
    });

    layui.use('form', function() {
        var form = layui.form;

        //监听提交
        form.on('submit(formDemo)', function(data) {
            let params = new FormData();
            params.append('address', data.field.address);
            params.append('area', data.field.area);
            params.append('cellphone', data.field.cellphone);
            params.append('chargePerson', data.field.chargePerson);
            params.append('constructCompany', data.field.constructCompany);
            params.append('contractCompany', data.field.contractCompany);
            params.append('finishDate', data.field.finishDate);
            params.append('fireOperateLevel', data.field.fireOperateLevel);
            params.append('investorCompany', data.field.investorCompany);
            params.append('name', data.field.name);
            params.append('shortName', data.field.shortName);
            params.append('startDate', data.field.startDate);
            params.append('superviseCompany', data.field.superviseCompany);
            params.append('type', data.field.type);
            params.append('status', data.field.status);
            params.append('longitude', data.field.longitude);
            params.append('latitude', data.field.latitude);

			//新加字段
			params.append('constructCompanyManager', data.field.constructCompanyManager);
			params.append('constructCompanyManagerPhone', data.field.constructCompanyManagerPhone);
			params.append('superviseCompanyDirector', data.field.superviseCompanyDirector);
			params.append('superviseCompanyDirectorPhone', data.field.superviseCompanyDirectorPhone);
			params.append('designCompany', data.field.designCompany);
			params.append('designCompanyTechnical', data.field.designCompanyTechnical);
			params.append('designCompanyLevel', data.field.designCompanyLevel);
			params.append('designCompanyPm', data.field.designCompanyPm);
			params.append('designCompanyPmQualification', data.field.designCompanyPmQualification);
			params.append('designCompanyPmPhone', data.field.designCompanyPmPhone);
			params.append('designCompanySafety', data.field.designCompanySafety);
			params.append('designCompanySafetyQualification', data.field.designCompanySafetyQualification);
			params.append('designCompanySafetyPhone', data.field.designCompanySafetyPhone);
			params.append('constructionSafetyObjectives', data.field.constructionSafetyObjectives);
			params.append('constructionCivilizationGoal', data.field.constructionCivilizationGoal);
			params.append('safetySupervisionNo', data.field.safetySupervisionNo);
			params.append('safetySupervisionDate', data.field.safetySupervisionDate);
			params.append('constructionCost', data.field.constructionCost);
			params.append('constructionStructure', data.field.constructionStructure);


            if ($('#imagefil')[0].files[0]) {
                params.append('file', $('#imagefil')[0].files[0]);
            } else {

            }
			if ($('#imagefil-plan')[0].files[0]) {
			    params.append('drawFile', $('#imagefil-plan')[0].files[0]);
			} else {
			
			}

            addSite(params)
            return false;
        });
    });
})

var areaCode = '';
var prarms = {};
var isPar = true;
//工地表格
function loadSiteTable(prarms) {
    if (prarms) {
        name = prarms.name;
    } else {
        var name = '';
    }

    layui.use('table', function() {
        var table = layui.table;
        //第一个实例
        table.render({
            title: '',
            text: {
                none: '暂无数据'
            },
            elem: '#main-right-table',
            skin: 'nob',
            url: ajaxPrefix() + '/manage/project/list',
            headers: { SessionId: localStorage.getItem('sessionId') },
            where: {
                pageSize: 10,
                areaCode: areaCode,
                name: name,
            },
            parseData: function(res) { //res 即为原始返回的数据
                return {
                    "code": res.status == 200 ? 0 : 1, //解析接口状态
                    "msg": res.message, //解析提示文本
                    "count": res.result.total, //解析数据长度
                    "data": res.result.data //解析数据列表
                };
            },
            request: {
                pageName: 'pageNum' //页码的参数名称，默认：page
                    ,
                limitName: 'pageSize' //每页数据量的参数名，默认：limit
            },
            page: {
                limit: 10,
            } //开启分页
            ,
            cols: [
                [ //表头
                    {
                        field: 'shortName',
                        title: '工地简称',
                        align: 'center'
                    }, {
                        field: 'name',
                        title: '工地名称',
                        align: 'center'
                    }, {
                        field: 'address',
                        title: '工程地址',
                        align: 'center',
                    }, {
                        field: 'area',
                        title: '施工面积(m²)',
                        align: 'center'
                    }, {
                        field: 'startDate',
                        title: '开工日期',
                        align: 'center'
                    }, {
                        field: 'type',
                        title: '工地类型',
                        align: 'center',
                    }, {
                        field: 'status',
                        title: '当前状态',
                        align: 'center'
                    }, {
                        title: '操作',
                        align: 'center',
                        width: 120,
                        templet: function(d) {
                            return `<div>
                            <div class="table-tool">
                                    <div onclick='showDetailsSite(${d.id})'><img src="../static/img/images/icon36.png">详情</div>
                                    <div onclick='deleteSite(${d.id})'><img src="../static/img/images/icon38.png">删除</div>
                                  </div>
                                  </div>`
                        },
                    },
                ]
            ]
        });
    });
}






showMenu = (res) => {

    $('.main-left-nav').toggle();
    $('.main-left-tree').toggle();

}



/*树*/
var setting = {
    async: {
        autoParam: ["id"],
        enable: true,
        url: getAsyncUrl,
        type: "get",
        dataFilter: ajaxDataFilter,
        headers: { "SessionId": localStorage.getItem('sessionId') },
    },
    view: {
        expandSpeed: "fast",
        fontCss: getFont,
        showLine: true,
        dblClickExpand: false,
        showIcon: false
    },
    callback: {
        onAsyncSuccess: zTreeOnAsyncSuccess,
        onClick: zTreeOnClick,
        beforeExpand: beforeExpand,
        onExpand: onExpand
    },
    data: {
        key: {
            title: "name"
        },
        simpleData: {
            enable: true,
            idKey: "code",
            pIdKey: "parentCode"
        }
    }
};

var zNodes;

function reloadTree() {
    zTree = $.fn.zTree.init($("#treeDemo"), setting);
}

function getAsyncUrl(treeId, treeNode) {
    if (!treeNode) {
        url = ajaxPrefix() + "/area/tree?areaCode=" + 320113;
    } else {
        url = ajaxPrefix() + "/area/projecttree?areaCode=" + treeNode.id;
    }

    return url;
}
//异步数据过滤
function ajaxDataFilter(treeId, parentNode, childNodes) {

    return childNodes;
}

//异步加载成功
function zTreeOnAsyncSuccess(event, treeId, treeNode, msg) {
    if (!treeNode) { //根节点
        var rootNode = zTree.getNodesByParam("level", 0)[0];
        return;
    }

    var selTreeId = _selTreeId;
    if (!!selTreeId) {
        var selNode = zTree.getNodeByParam("id", selTreeId);
        if (!!selNode) {
            _selTreeId = null;
            zTree.selectNode(selNode);
            zTreeOnClick();
        }
    }
}
//获取选中的节点
function getSelectedNode() {
    var treeNode = zTree.getSelectedNodes();
    if (treeNode.length == 0) {

        return false;
    }
    return treeNode[0];
}

//刷新子节点并确定要选中节点ID
var _selTreeId = null;

function reloadNode(refreshId, isParent, selTreeId) {
    var node = zTree.getNodeByParam("id", refreshId);
    if (!!node && !!isParent) {
        node = node.getParentNode();
        if (!node) {
            _selTreeId = selTreeId;
            reloadTree();
            return;
        }
    }
    if (!!node) {
        _selTreeId = selTreeId;
        zTree.reAsyncChildNodes(node, "refresh");
    }
}


//右击事件
function getFont(treeId, node) {
    return node.font ? node.font : {};
}
//仅能打开一个子节点
var curExpandNode = null;

function beforeExpand(treeId, treeNode) {
    var pNode = curExpandNode ? curExpandNode.getParentNode() : null;
    var treeNodeP = treeNode.parentTId ? treeNode.getParentNode() : null;
    for (var i = 0, l = !treeNodeP ? 0 : treeNodeP.children.length; i < l; i++) {
        if (treeNode !== treeNodeP.children[i]) {
            zTree.expandNode(treeNodeP.children[i], false);
        }
    }
    while (pNode) {
        if (pNode === treeNode) {
            break;
        }
        pNode = pNode.getParentNode();
    }
    if (!pNode) {
        singlePath(treeNode);
    }

}

function singlePath(newNode) {
    if (newNode === curExpandNode) return;
    if (curExpandNode && curExpandNode.open == true) {
        var zTree = $.fn.zTree.getZTreeObj("treeDemo");
        if (newNode.parentTId === curExpandNode.parentTId) {
            zTree.expandNode(curExpandNode, false);
        } else {
            var newParents = [];
            while (newNode) {
                newNode = newNode.getParentNode();
                if (newNode === curExpandNode) {
                    newParents = null;
                    break;
                } else if (newNode) {
                    newParents.push(newNode);
                }
            }
            if (newParents != null) {
                var oldNode = curExpandNode;
                var oldParents = [];
                while (oldNode) {
                    oldNode = oldNode.getParentNode();
                    if (oldNode) {
                        oldParents.push(oldNode);
                    }
                }
                if (newParents.length > 0) {
                    zTree.expandNode(oldParents[Math.abs(oldParents.length - newParents.length) - 1], false);
                } else {
                    zTree.expandNode(oldParents[oldParents.length - 1], false);
                }
            }
        }
    }
    curExpandNode = newNode;
}

function onExpand(event, treeId, treeNode) {
    curExpandNode = treeNode;
}

//单击树节点事件
function zTreeOnClick(event, treeId, treeNode) {
    isPar = treeNode.isParent;
    areaCode = treeNode.code;
    loadSiteTable();
}


/*工地详情*/
showDetailsSite = (projectId) => {
    $('.detail-body>ul').html('');
	Ajax('/manage/project/detail?id=' + projectId, callBack);

    function callBack(res) {
        var data = res.result
        let str = '';
		str = ` <div class="layui-tab-item layui-show">
					<ul class="detail-ul"><li class="detail-body-item">
								<div>工地简称：</div>
								<span>${data.shortName}</span>
							</li>
							<li class="detail-body-item">
								<div>工地名称：</div>
								<span>${data.name}</span>
							</li>
							<li class="detail-body-item">
								<div>工程地址：</div>
								<span>${data.address}</span>
							</li>
							<li class="detail-body-item">
								<div>施工面积：</div>
								<span>${data.area}m²</span>
							</li>
							<li class="detail-body-item">
								<div>工程造价：</div>
								<span>${data.constructionCost}</span>
							</li>
							<li class="detail-body-item">
								<div>结构层次：</div>
								<span>${data.constructionStructure}</span>
							</li>
							<li class="detail-body-item">
								<div>投资方：</div>
								<span>${data.investorCompany}</span>
							</li>
							<li class="detail-body-item">
								<div>建筑方：</div>
								<span>${data.constructCompany}</span>
							</li>
							<li class="detail-body-item">
								<div>施工方：</div>
								<span>${data.contractCompany}</span>
							</li>
							<li class="detail-body-item">
								<div>监理方：</div>
								<span>${data.superviseCompany}</span>
							</li>
							<li class="detail-body-item">
								<div>开工日期：</div>
								<span>${data.startDate}</span>
							</li>
							<li class="detail-body-item">
								<div>完工日期：</div>
								<span>${data.finishDate}</span>
							</li>
							<li class="detail-body-item">
								<div>工地类型：</div>
								<span>${data.type}</span>
							</li>
							<li class="detail-body-item">
								<div>动火级别：</div>
								<span>${data.fireOperateLevel}</span>
							</li>
							<li class="detail-body-item">
								<div>总负责人：</div>
								<span>${data.chargePerson}</span>
							</li>
							<li class="detail-body-item">
								<div>联系电话：</div>
								<span> ${data.cellphone}</span>
							</li>
							<li class="detail-body-item">
								<div>经纬度：</div>
								<span>${data.longitude}——${data.latitude}</span>
							</li>
							<li class="detail-body-item">
								<div>工地状态：</div>
								<span>${data.status}</span>
							</li>
							<li class="detail-body-item">
								<div>现场照片：</div>
								<img class="imagesBox" src="/images/${data.imagePath}">
							</li>
							<li class="detail-body-item">
								<div>平面图：</div>
								<img class="imagesBox" src="/images/${data.drawPath}">
							</li></ul>
				</div>
				<div class="layui-tab-item">
					<ul class="detail-ul"><li class="detail-body-item">
						<div>建设单位：</div>
						<span>${data.constructCompany}</span>
					</li>
					<li class="detail-body-item">
						<div style="width:1rem">现场负责人：</div>
						<span>${data.constructCompanyManager}</span>
					</li>
					<li class="detail-body-item">
						<div>联系电话：</div>
						<span>${data.constructCompanyManagerPhone}</span>
					</li></ul>
				</div>
				<div class="layui-tab-item">
					<ul class="detail-ul"><li class="detail-body-item">
						<div>监理单位：</div>
						<span>${data.superviseCompany}</span>
					</li>
					<li class="detail-body-item">
						<div>项目总监：</div>
						<span>${data.superviseCompanyDirector}</span>
					</li>
					<li class="detail-body-item">
						<div>联系电话：</div>
						<span>${data.superviseCompanyDirectorPhone}</span>
					</li></ul>
				</div>
				<div class="layui-tab-item">
					<ul class="detail-ul"><li class="detail-body-item">
						<div style="width:1rem">勘察设计单位：</div>
						<span>${data.designCompany}</span>
					</li>
					<li class="detail-body-item">
						<div style="width:1rem">项目技术负责人：</div>
						<span>${data.designCompanyTechnical}</span>
					</li>
					<li class="detail-body-item">
						<div>施工单位：</div>
						<span>${data.contractCompany}</span>
					</li>
					<li class="detail-body-item">
						<div>资质等级：</div>
						<span>${data.designCompanyLevel}</span>
					</li>
					<li class="detail-body-item">
						<div>项目经理：</div>
						<span>${data.designCompanyPm}</span>
					</li>
					<li class="detail-body-item">
						<div style="width:1.4rem">经理安全考核合格证号：</div>
						<span>${data.designCompanyPmQualification}</span>
					</li>
					<li class="detail-body-item">
						<div>经理电话：</div>
						<span>${data.designCompanyPmPhone}</span>
					</li>
					<li class="detail-body-item">
						<div>安全员：</div>
						<span>${data.designCompanySafety}</span>
					</li>
					<li class="detail-body-item">
						<div style="width:1.6rem">安全员安全考核合格证号：</div>
						<span>${data.designCompanySafetyQualification}</span>
					</li>
					<li class="detail-body-item">
						<div style="width:1rem">安全员电话：</div>
						<span>${data.designCompanySafetyPhone}</span>
					</li>
					<li class="detail-body-item">
						<div style="width:1.2rem">工程安全管理目标：</div>
						<span>${data.constructionSafetyObjectives}</span>
					</li>
					<li class="detail-body-item">
						<div style="width:1.2rem">文明施工创建目标：</div>
						<span>${data.constructionCivilizationGoal}</span>
					</li>
					<li class="detail-body-item">
						<div style="width:1rem">安全监督备案号：</div>
						<span>${data.safetySupervisionNo}</span>
					</li>
					<li class="detail-body-item">
						<div style="width:1rem">监督备案日期：</div>
						<span>${data.safetySupervisionDate}</span>
					</li></ul>
				</div>`;
		// str = ``
        $('#detail_content').html(str);

    }

    $('.detail').show();
}

/*删除动火点*/
deleteSite = (projectId) => {
    layer.confirm('确认删除吗？</br>删除后无法恢复，请谨慎操作', { title: '提示' }, function() {
        Ajax('/manage/project/delete?id=' + projectId, callBack)

        function callBack(res) {
            if (res.status == 200) {
                layer.msg('删除成功', { time: 1000 })
                loadSiteTable();
            } else {
                layer.msg('删除失败！', { icon: 2, time: 1000 })
            }
        }
    });
}


$('button.search-button').click(function() {
    prarms.name = $('#project-name').val();
    loadSiteTable(prarms);
})
$('div.search-button').click(function() {
    if (isPar) {
        layer.msg('请先在右侧选择所属街道')
    } else {
        $('.add-site').show();
    }

})
/*新增工地*/
addSite = (params) => {
    params.append('areaCode', areaCode);
    $.ajax({
        url: ajaxPrefix() + '/manage/project/add',
        type: 'post',
        data: params,
        dataType: "json",
        beforeSend: function(XMLHttpRequest) {
            XMLHttpRequest.setRequestHeader("SessionId", localStorage.getItem('sessionId'));
        },
        cache: false,
        processData: false,
        contentType: false,
        success: function(res) {
            if (res.status == 200) {
                layer.msg('新增成功', { time: 1000 });
                $(".add-site>.main-tit>div").click();
                loadSiteTable();
            } else {
                layer.msg('操作失败！', { time: 1000 })
            }

        }
    });

}
$(".add-site>.main-tit>div").click(function() {
    $('.add-site').hide();
    $('#reset').click();
    $('.map-box').hide();
    $('.add-site-body').show();
    map && map.destroy();
    $('#upload-image').show();
    $('#image-callback').hide();
    $("#image-callback").attr('src', '');
	$('#upload-image-plan').show();
	$('#image-callback-plan').hide();
	$("#image-callback-plan").attr('src', '');
})
$('.upload-image-plan').click(function() {
    $('.file-input-plan').click();
})
function changenameplan(files) {
    $('.upload-image-plan').attr('value', $('.file-input-plan').val());
    let file = files.files[0];
	console.log(file);
    if (file) {
        var reader = new FileReader();
        reader.onload = function(evt) {
            $('#upload-image-plan').hide();
            $('#image-callback-plan').show();
            $("#image-callback-plan").attr('src', evt.target.result);
        }
        reader.readAsDataURL(file);
    } else {
        // $(".upload-image-plan").html('图片上传失败');
    }
}
$('.upload-image').click(function() {
    $('.file-input').click();
})
function changename(files) {
    $('.upload-image').attr('value', $('.file-input').val());
    let file = files.files[0];
    if (file) {
        var reader = new FileReader();
        reader.onload = function(evt) {
            $('#upload-image').hide();
            $('#image-callback').show();
            $("#image-callback").attr('src', evt.target.result);
        }
        reader.readAsDataURL(file);
    } else {
        $(".upload-image").html('图片上传失败');
    }
}

var map;
/*地图*/
$('#map-input').click(function() {
    $('.add-site-body').hide();
    $('.map-box').show();
    map = new AMap.Map('map', {
        zoom: 13,
        center: [121.404195, 31.186536],
        mapStyle: 'amap://styles/6f2ac55a0fce7bb44145e64373f74f99',

    });
    map.on('click', function(e) {
        $('.add-site-body').show();
        $('.map-box').hide();
        $('#map-input').val(e.lnglat.getLng() + ',' + e.lnglat.getLat());
        $('input[name=longitude]').val(e.lnglat.getLng());
        $('input[name=latitude]').val(e.lnglat.getLat());
    });
    AMapUI.loadUI(['misc/PoiPicker'], function(PoiPicker) {

        var poiPicker = new PoiPicker({
            input: 'pickerInput'
        });

        //初始化poiPicker
        poiPickerReady(poiPicker);
    });

    function poiPickerReady(poiPicker) {

        window.poiPicker = poiPicker;

        var marker = new AMap.Marker();

        var infoWindow = new AMap.InfoWindow({
            offset: new AMap.Pixel(0, -20)
        });
        marker.on('click', function(e) {
            $('.add-site-body').show();
            $('.map-box').hide();
            $('#map-input').val(e.lnglat.getLng() + ',' + e.lnglat.getLat());
            $('input[name=longitude]').val(e.lnglat.getLng());
            $('input[name=latitude]').val(e.lnglat.getLat());
        });
        //选取了某个POI
        poiPicker.on('poiPicked', function(poiResult) {

            var poi = poiResult.item;

            marker.setMap(map);

            marker.setPosition(poi.location);


            map.setFitView();
        });

    }
})